package cn.ymatrix.copyToYMatrix;

import cn.ymatrix.logger.LoggerLevel;
import cn.ymatrix.logger.MxLogger;
import cn.ymatrix.utils.Config;
import org.postgresql.copy.CopyManager;
import org.postgresql.core.BaseConnection;
import org.slf4j.Logger;

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class CopyFileTOYMatrix {

  public static void main(String[] args) throws IOException {

    MxLogger.loggerLevel(LoggerLevel.INFO);
    Logger LOGGER = MxLogger.init(CopyFileTOYMatrix.class);

    String copySql =
        "COPY "
            + Config.getTableName()
            + " FROM STDIN DELIMITER E'"
            + Config.getDelimiter()
            + "' CSV";

    Connection connection = null;
    FileReader fileReader = null;
    long batchStartTime = System.currentTimeMillis();

    try {
      LOGGER.info("---- 开始插入数据 ----");
      Class.forName(Config.getDRIVER_CLASS_NAME());
      connection =
          DriverManager.getConnection(Config.getUrl(), Config.getUserName(), Config.getPassWord());
      CopyManager copyManager = new CopyManager((BaseConnection) connection);
      fileReader = new FileReader(Config.getCsvFilePath());
      Long lineSum = copyManager.copyIn(copySql, fileReader);
      long batchEndTime = System.currentTimeMillis() - batchStartTime;
      LOGGER.info("成功插入 " + lineSum + " 条数据,耗时: " + batchEndTime + "毫秒");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      fileReader.close();
    }
    if (connection != null) {
      try {
        connection.close();
      } catch (SQLException e) {
        LOGGER.error("connection close error " + e.getMessage());
      }
    }
  }
}
